import { getDictsApi } from "@/api/system/dict";

const state = {
  dict: {},
};
const mutations = {
  SET_DICT: (state, { key, value }) => {
    if (key !== null && key !== "") {
      state.dict[key] = value;
    }
  },
  REMOVE_DICT: (state, key) => {
    try {
      delete state.dict[key];
    } catch (e) {}
  },
  CLEAN_DICT: (state) => {
    state.dict = {};
  },
};

const actions = {
  // 设置字典
  setDict({ commit }, types) {
    const permData = [];
    const returnData = {};
    types.forEach((dictType) => {
      if (state.dict[dictType]) {
        returnData[dictType] = state.dict[dictType];
      } else {
        permData.push(dictType);
      }
    });
    if (permData.length === 0) {
      return returnData;
    }
    return new Promise((resolve, reject) => {
      getDictsApi(permData)
        .then((res) => {
          if (res) {
            for (const key in res) {
              returnData[key] = res[key];
              commit("SET_DICT", {
                key,
                value: res[key],
              });
            }
          }
          resolve(returnData);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // 删除字典
  removeDict({ commit }, key) {
    commit("REMOVE_DICT", key);
  },
  // 清空字典
  cleanDict({ commit }) {
    commit("CLEAN_DICT");
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
